package cn.stylefeng.roses.seata.demo.storage.modular.service.impl;

import cn.stylefeng.roses.seata.demo.storage.core.BlockedStorage;
import cn.stylefeng.roses.seata.demo.storage.modular.service.StorageTblService;
import cn.stylefeng.roses.seata.demo.storage.modular.service.TccSubStorageService;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * TCC方式实现扣减库存的方法
 *
 * @author fengshuonan
 * @date 2021/10/13 21:36
 */
@Service
public class TccSubStorageServiceImpl implements TccSubStorageService {

    @Resource
    private StorageTblService storageTblService;

    @Override
    public void subStorageTry(String commodityCode, int count) {
        // 模拟冻结库存
        BlockedStorage.set(count);
    }

    @Override
    public boolean subStorageConfirm(BusinessActionContext context) {

        String commodityCode = (String) context.getActionContext("commodityCode");
        Integer count = (Integer) context.getActionContext("count");

        // 真正扣减库存
        storageTblService.subStorage(commodityCode, count);

        return true;
    }

    @Override
    public boolean subStorageCancel(BusinessActionContext context) {

        // 模拟恢复库存
        BlockedStorage.set(0);

        return true;
    }

}